<script setup lang="ts">
import { getHomeBannerApi, getCategoryMutliApi, getHomeHotMutliApi } from '@/services/home'
import type { bannerItem, categoryItem, HomeHotItem } from '@/types/home'
import { onLoad } from '@dcloudio/uni-app'
import { ref } from 'vue'
import CustomNavbar from './components/CustomNavbar.vue'
import CategoryPanel from './components/CategoryPanel.vue'
import HotPanel from './components/HotPanel.vue'
import PageSkeleton from './components/PageSkeleton.vue'
import { useGuessList } from '@/composables'

const bannerList = ref<bannerItem[]>([])
const categoryList = ref<categoryItem[]>([])
const homeHotList = ref<HomeHotItem[]>([])
const isTriggered = ref(false)
// 获取首页轮播图数据
const getHomeBannerData = async () => {
  const res = await getHomeBannerApi()
  bannerList.value = res.result
}
// 获取首页分类数据
const getCategoryMutliData = async () => {
  const res = await getCategoryMutliApi()
  categoryList.value = res.result
}
// 获取热门推荐数据
const getHomeHotMutliData = async () => {
  const res = await getHomeHotMutliApi()
  homeHotList.value = res.result
}
// 调用猜你喜欢的组合式函数
const { guessRef, onScrolltolower } = useGuessList()

// 自定义下拉事件
const onRefresherrefresh = async () => {
  // 开始动画
  isTriggered.value = true
  guessRef.value?.resetData()
  await Promise.all([getHomeBannerData(), getCategoryMutliData(), getHomeHotMutliData()])
  guessRef.value?.getMore()
  // 关闭动画
  isTriggered.value = false
}
// 是否加载数据中
const isLoading = ref(false)
// 页面加载
onLoad(async () => {
  isLoading.value = true
  await Promise.all([getHomeBannerData(), getCategoryMutliData(), getHomeHotMutliData()])
  isLoading.value = false
})
</script>

<template>
  <!-- 头部导航栏 -->
  <CustomNavbar />
  <!-- 添加滚动容器 -->
  <scroll-view
    refresher-enabled
    :refresher-triggered="isTriggered"
    @refresherrefresh="onRefresherrefresh"
    @scrolltolower="onScrolltolower"
    scroll-y
    class="scroll-view"
  >
    <PageSkeleton v-if="isLoading" />
    <template v-else>
      <!-- 轮播图 -->
      <XtxSwiper :list="bannerList" />
      <!-- 分类面板 -->
      <CategoryPanel :list="categoryList" />
      <!-- 热门推荐 -->
      <HotPanel :lsit="homeHotList" />
      <!-- 猜你喜欢 -->
      <XtxGuess ref="guessRef" />
    </template>
  </scroll-view>
</template>

<style lang="scss">
page {
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: #f7f7f7;
}
.scroll-view {
  flex: 1;
}
</style>
